package live.jipiao.dao;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.TreeMap;

import live.common.AirParam;
import live.common.Format;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;


@SuppressWarnings("unchecked")
public class XmlFormart {

	private static XmlFormart instance=null;
	public static synchronized XmlFormart getInstance() {
		if(instance==null){
			instance=new XmlFormart();
		}
		return instance;
	}
	
	private String result = null;
	
	/**
	 * 将xml串转换Document对象
	 * @param xmlStr
	 * @return
	 * @throws DocumentException
	 */
	public Document xmlToDocument(String xmlStr)
			throws DocumentException {
			return DocumentHelper.parseText(xmlStr.trim());
	}

	/**
	 * 匹配单个节点
	 * @param e
	 * @param nodeName
	 * @param qName
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	public String returnXmlNodeValue(Element e, String nodeName,
			String qName) throws UnsupportedEncodingException {
		String xpath = new StringBuffer("./").append(nodeName).append(
				"[@name='").append(qName).append("']").toString();
		result = ((Element) e.selectSingleNode(xpath)).attributeValue("value");
		return Format.getInstance().decoedGB2312(result);
	}
	
	public  String returnSingleNode(Document doc,String xpath){
		result = ((Element)doc.selectNodes(xpath).get(0)).getTextTrim();
		return result;
	}

	/**
	 * 匹配节点数据集
	 * @param doc	Document对象
	 * @param xpath 表达式
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	public List returnElements(Document doc, String xpath)
			throws UnsupportedEncodingException {
		List results = null;
		List nodes = doc.selectNodes(xpath);
		if (nodes != null && nodes.size() > 0) {
			results = new ArrayList();
			Iterator iter = nodes.iterator();
			while (iter.hasNext()) {
				Element e = (Element) iter.next();
				results.add(e);
			}
		}
		return results;
	}
	
	/**
	 * 公共参数部分
	 * @param mehtod_name
	 * @return
	 */
	public TreeMap<String, String> returnPublicPostData(String mehtod_name){
		TreeMap<String, String> params = new TreeMap<String, String>();
		params.put("service", mehtod_name);
		params.put("partner", AirParam.AIR_PARTNER.toString());
		return params;
	}
}
